package com.weichuanbo.xwdz.mvp.model.api;
import com.weichuanbo.xwdz.mvp.model.api.service.ApiServer;
import com.weichuanbo.xwdz.mvp.model.entity.BaseResponse;

import java.util.concurrent.TimeUnit;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import okhttp3.OkHttpClient;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/6/17.
 */

public class RetrofitHelper {

    public static final String TAG=RetrofitHelper.class.getSimpleName();
    public static final String BASE_URL = Api.APP_HOST;
    private static final int DEFAULT_TIMEOUT = 20;
    private ApiServer apiManager;
    private Retrofit retrofit;

    /**
     * 创建私有构造函数  只能在本类中进行初始化
     */
    private RetrofitHelper() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        OkHttpClient client = builder
                //设置缓存
                //      .cache(new Cache(httpCacheDirectory, 10 * 1024 * 1024))
                //log请求参数

                .build();
        //实例化 retrofit对象
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
//                .client(builder.build())
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiManager=retrofit.create(ApiServer.class);
    }

    /**
     * 创建HttpMethod实例
     */
    public static class SingleInstance {
        private static final RetrofitHelper INSTANCE = new RetrofitHelper();
    }

    /**
     * 获得HttpMethod实例
     *
     * @return
     */
    public static RetrofitHelper getInstance() {
        return SingleInstance.INSTANCE;
    }


    /**
     * 获取ApiManger实例
     * @return
     */
    public ApiServer getApiManager(){
        return apiManager;
    }

    /**
     * 用来统一处理Http的ResultCode,并将HttpResult的data部分剥离出来返还给observer
     *
     * @param <T> Observer 真正用的的数据就是HttpResult中的data
     */
    public static class HttpResultFuct<T> implements Function<BaseResponse<T>, T> {
        @Override
        public T apply(@NonNull BaseResponse<T> tHttpResult) throws Exception {

            if (!tHttpResult.isSuccess())    //请求失败
                throw new ApiException(tHttpResult.getMsg(),tHttpResult.getStatus()); //抛出自定义异常
            return tHttpResult.getData();
        }
    }


}
